import {
  getMemorys,
  getVisitors,
  handleMemory,
  handleVisitor,
  visitorEvents,
} from "@/services"
import {
  ActionType,
  PageContainer,
  ProColumns,
  ProTable,
} from "@ant-design/pro-components"
import { Box } from "@mui/system"
import { useRequest } from "ahooks"
import {
  Button,
  Collapse,
  DatePicker,
  Drawer,
  Form,
  message,
  Modal,
  Popconfirm,
  Popover,
  Space,
  Spin,
  Tag,
  Typography,
} from "antd"
import { SortOrder } from "antd/es/table/interface"
import dayjs from "dayjs"
import React, { useEffect, useRef, useState } from "react"
import TagInput from "./components/TagInput"
import { EditOutlined, EyeOutlined } from "@ant-design/icons"
import IpDetail from "./components/IpDetail"
import { useNavigate } from "react-router-dom"

export default () => {
  const Action = useRef<ActionType | undefined>(null)
  const [editStatus, setEditStatus] = useState<any>(null)
  const [form] = Form.useForm()
  const { runAsync, loading } = useRequest((params) => getVisitors(params), {
    manual: true,
  })

  const { runAsync: editMemory, loading: editMemoryLoading } = useRequest(
    handleVisitor,
    {
      manual: true,
      onSuccess(data, params) {
        Action.current?.reload()
      },
    },
  )
  const navigate = useNavigate()
  const [detailRecord, setDetailRecord] = useState<any>(null)

  const requester = async (
    { current, pageSize, ...params }: any,
    sort: Record<string, SortOrder>,
    filter: Record<string, (string | number)[] | null>,
  ) => {
    const sortParams: any = {}
    Object.keys(sort)?.forEach?.((key) => {
      sortParams[key] = sort[key] === "ascend" ? "asce" : "desc"
    })
    const res = await runAsync({ pageSize, pageNo: current, ...sortParams })
    return res?.data
  }
  const {
    runAsync: runGetDetail,
    data,
    loading: tarcksLoading,
  } = useRequest(visitorEvents, {
    manual: true,
  })
  const columns: ProColumns<any>[] = [
    {
      title: "用户ID",
      dataIndex: "fingerprint_key",
      renderText(text, record, index, action) {
        return text
      },
    },
    {
      title: "最近访问IP",
      dataIndex: "last_ip",
      render(dom, entity, index, action, schema) {
        return entity?.last_ip ? (
          <Popover
            trigger={"click"}
            content={<IpDetail ip={entity?.last_ip}></IpDetail>}
          >
            <Button type="link" icon={<EyeOutlined></EyeOutlined>}>
              {entity?.last_ip}
            </Button>
          </Popover>
        ) : (
          "-"
        )
      },
    },
    {
      title: "标签",
      dataIndex: "tags",
      hideInSearch: true,
      width: 80,
      render(tags, record, index, action) {
        const defaultTag = record?.tags?.[0] ?? "访客"
        return (
          <Popover
            content={
              record?.tags?.length &&
              record?.tags?.map((item: string) => (
                <Tag color={item === "本机" ? "error" : "default"}>{item}</Tag>
              ))
            }
          >
            <Tag
              style={{ cursor: "pointer" }}
              color={defaultTag === "本机" ? "error" : "default"}
            >
              {defaultTag}
            </Tag>
          </Popover>
        )
      },
    },
    {
      title: "最近访问时间",
      dataIndex: "last_visit",
      sorter: true,
      renderFormItem(schema, config, form, action) {
        return (
          <DatePicker.RangePicker
            allowEmpty={[true, true]}
            onChange={(dates, datesring) => {}}
          />
        )
      },
      renderText(text, record, index, action) {
        return dayjs(text)?.format("YYYY-MM-DD HH:mm:ss")
      },
    },
    {
      title: "初次访问时间",
      dataIndex: "first_visit",
      renderFormItem(schema, config, form, action) {
        return (
          <DatePicker.RangePicker
            allowEmpty={[true, true]}
            onChange={(dates, datesring) => {}}
          />
        )
      },
      renderText(text, record, index, action) {
        return dayjs(text)?.format("YYYY-MM-DD HH:mm:ss")
      },
    },
    {
      title: "累计活动次数",
      dataIndex: "eventsCount",
      renderText(text, record, index, action) {
        return text
      },
    },
    {
      title: "操作",
      dataIndex: "action",
      width: 200,
      hideInSearch: true,
      renderText(text, record, index, action) {
        return (
          <>
            <Box className="space-x-2">
              <Button
                type="link"
                icon={<EyeOutlined></EyeOutlined>}
                onClick={() => {
                  //runGetDetail({ id: record?.fingerprint_key, pageSize: 9999 })
                  //navigate(`tracks?user=${record?.fingerprint_key}`)
                  setDetailRecord(record)
                  runGetDetail({
                    id: record?.fingerprint_key,
                    pageSize: 9999,
                  })
                }}
              >
                查看
              </Button>
              <Button
                onClick={() => {
                  setEditStatus(record)
                }}
                icon={<EditOutlined></EditOutlined>}
                type="link"
              >
                编辑
              </Button>
            </Box>
          </>
        )
      },
    },
  ]
  useEffect(() => {
    form.setFieldsValue(editStatus)
  }, [editStatus])
  return (
    <PageContainer
      title={"访客"}
      style={{ minWidth: "fit-content" }}
      subTitle={"Visitors"}
    >
      <Spin spinning={editMemoryLoading}>
        <Modal
          title="编辑"
          okText={"保存"}
          onCancel={() => {
            setEditStatus(null)
            form.resetFields()
          }}
          onOk={() => {
            form.validateFields().then((res) => {
              editMemory({ ...res, id: editStatus?.fingerprint_key })
                .then((res) => {
                  setEditStatus(null)
                  message.success("保存成功")
                })
                .catch((e) => {
                  message.error("修改失败请重试")
                })
            })
          }}
          open={editStatus}
        >
          <Form form={form}>
            <Form.Item initialValue={[]} name={"tags"} label={"标签"}>
              <TagInput></TagInput>
            </Form.Item>
          </Form>
        </Modal>
      </Spin>
      <ProTable
        actionRef={Action}
        rowSelection={{
          type: "checkbox",
          onChange(selectedRowKeys, selectedRows, info) {},
          preserveSelectedRowKeys: true,
        }}
        rowKey={"id"}
        tableAlertOptionRender={({
          intl: IntlType,
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Box className="space-x-2">
            <Button type="primary" onClick={() => {}} size="small">
              批量编辑
            </Button>
          </Box>
        )}
        columns={columns}
        loading={loading}
        request={requester}
      ></ProTable>
      <Drawer
        open={detailRecord}
        placement="bottom"
        height={"80vh"}
        onClose={() => setDetailRecord(null)}
        title={"详情"}
      >
        <Spin spinning={tarcksLoading}>
          <Collapse
            items={data?.data?.data?.map(
              (
                { t, event, url, referer, userAgent, ...item }: any,
                index: number,
              ) => {
                return {
                  label: (
                    <div className="flex items-center">
                      <div style={{ minWidth: 80 }}>
                        <Tag color={"blue"}>{event}</Tag>
                      </div>
                      {dayjs(t).format("YYYY-MM-DD HH:mm:ss")}
                    </div>
                  ),
                  children: (
                    <div className="flex flex-col">
                      <Form layout="inline">
                        <Form.Item label={"来源"}>
                          <Typography.Paragraph
                            style={{ margin: 0 }}
                            ellipsis={{ rows: 2, tooltip: referer }}
                          >
                            {referer ? <a href={referer}>{referer}</a> : "无"}
                          </Typography.Paragraph>
                        </Form.Item>
                        <Form.Item label={"地址"}>
                          <Typography.Paragraph
                            style={{ margin: 0 }}
                            ellipsis={{ rows: 2, tooltip: url }}
                          >
                            <a href={url} target={"_blank"}>
                              {url}
                            </a>
                          </Typography.Paragraph>
                        </Form.Item>
                        <Form.Item label={"设备"}>
                          <Typography.Paragraph
                            style={{ margin: 0 }}
                            ellipsis={{ rows: 2, tooltip: userAgent }}
                          >
                            {userAgent}
                          </Typography.Paragraph>
                        </Form.Item>
                      </Form>
                      <Typography.Paragraph>
                        <pre>{JSON.stringify(item, null, 2)}</pre>
                      </Typography.Paragraph>
                    </div>
                  ),
                }
              },
            )}
          />
        </Spin>
      </Drawer>
    </PageContainer>
  )
}
